package com.edu.demo.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.edu.demo.entity.UsersInfo;
import com.edu.demo.entity.dto.UserLoginDTO;
import com.edu.demo.entity.dto.UserLoginDTO2;
import com.edu.demo.entity.vo.RegisterByPhone2VO;
import com.edu.demo.entity.vo.UserLoginByPassVO;
import com.edu.demo.result.MyPage;
import com.edu.demo.result.Result;
import com.edu.demo.service.IUsersInfoService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 * 用户信息 前端控制器
 * </p>
 *
 * @author Ashe1y
 * @since 2024-03-13
 */
@Slf4j
@Api(tags = "用户信息")
@RestController
@RequestMapping("/users-info")
public class UsersInfoController {

    @Resource
    private IUsersInfoService usersInfoService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 查询个人信息
     *
     * @param id
     * @return
     */
    @ApiOperationSupport(author = "Ashe1y")
    @ApiOperation(value = "查询个人信息V2")
    @SaCheckLogin
    @GetMapping("/getInfoV2")
    public Result getInfoV2() {
        Integer id = StpUtil.getLoginIdAsInt();
        UsersInfo usersInfo = usersInfoService.selectById(id);
        return Result.success(usersInfo).msg("查询成功");
    }

    /**
     * 查询个人信息
     *
     * @param id
     * @return
     */
    @ApiOperationSupport(author = "Ashe1y")
    @ApiOperation(value = "查询个人信息(已弃用)")
    @GetMapping("/getInfo/{id}")
    public Result getInfo(@PathVariable String id) {
        //设置一个key
        String key = "userInfo"+id;
        //查Redis
        if (redisTemplate.hasKey(key)) {
            log.info("通过Redis查询");
            return Result.success(redisTemplate.opsForValue().get(key)).msg("查询成功");

        }
        log.info("通过数据库查询");
        //通过数据库查询
        UsersInfo usersInfo = usersInfoService.getById(id);
        //给Redis一份
        redisTemplate.opsForValue().set(key, usersInfo);
        return Result.success(usersInfo).msg("查询成功");
    }

    /**
     * 根据手机查询数据接口
     *
     * @param phone
     * @return
     */
    @ApiOperationSupport(author = "Ashe1y")
    @ApiOperation(value = "根据手机模糊查询数据接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", required = true)
    })
    @GetMapping("/findByPhone/{phone}")
    public Result<UserLoginDTO2> findByPhone(@PathVariable String phone) {
        List<UserLoginDTO2> byPhone = usersInfoService.findByPhone(phone);
        return Result.success(byPhone).msg("查询成功");
    }


    /**
     * 查询所有接口
     *
     * @return
     */
    @ApiOperationSupport(author = "Ashe1y")
    @ApiOperation(value = "查询用户信息所有数据")
    @GetMapping
    public Result<List<UsersInfo>> findAll() {
        return Result.success(usersInfoService.list()).msg("查询成功");
    }

    /**
     * 根据id查询数据接口
     *
     * @param id
     * @return
     */
    @ApiOperationSupport(author = "Ashe1y")
    @ApiOperation(value = "根据id查询数据接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "组件id", required = true)
    })
    @GetMapping("/{id}")
    public Result<UsersInfo> findOne(@PathVariable Integer id) {
        return Result.success(usersInfoService.getById(id)).msg("查询成功");
    }

    /**
     * 分页查询接口
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ApiOperationSupport(author = "Ashe1y")
    @ApiOperation(value = "分页查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", example = "1", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页多少条", example = "10", required = true)
    })
    @GetMapping("/page")
    public Result<MyPage<UsersInfo>> findPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        QueryWrapper<UsersInfo> queryWrapper = new QueryWrapper<>();
        return Result.success().data(usersInfoService.page(new Page<>(pageNum, pageSize), queryWrapper)).msg("查询成功");
    }


    /**
     * 注册接口
     *
     * @param
     * @return
     */
    @ApiOperationSupport(author = "Ashe1y")
    @ApiOperation(value = "注册")
    @PostMapping("/add")
    public Result<String> add(@Valid @RequestBody RegisterByPhone2VO registerByPhone2VO) {
        UsersInfo usersInfo = new UsersInfo();
        BeanUtil.copyProperties(registerByPhone2VO, usersInfo);
        usersInfoService.register(usersInfo);
        return Result.success().msg("注册成功");
    }

    /**
     * 登录
     *
     * @param
     * @return
     */
    @ApiOperationSupport(author = "Ashe1y")
    @ApiOperation(value = "登录")
    @PostMapping("/login")
//TODO 记得创建VO
    public Result<UserLoginDTO> login(@Valid @RequestBody UserLoginByPassVO userLoginByPassVO) {
        //TODO VO转entity
        UsersInfo usersInfo = new UsersInfo();
        BeanUtil.copyProperties(userLoginByPassVO, usersInfo);
        UserLoginDTO2 loginDTO = usersInfoService.login(usersInfo);
        StpUtil.login(loginDTO.getUserId());
        //保存登录信息
        StpUtil.login(loginDTO.getUserId())
        ;//获取当前会话的token
        String tokenValue = StpUtil.getTokenValue();
        //设置token
        loginDTO.setToken(tokenValue);
        return Result.success(loginDTO).msg("登录成功");
    }

    /**
     * 更新接口
     *
     * @param
     * @return
     */
    @ApiOperationSupport(author = "Ashe1y")
    @ApiOperation(value = "更新接口")
    @PutMapping("/update")
    public Result<String> update(@RequestBody UsersInfo usersInfo) {
        usersInfoService.saveOrUpdate(usersInfo);
        return Result.success().msg("修改成功");
    }


    /**
     * 删除接口
     *
     * @param id
     * @return
     */
    @ApiOperationSupport(author = "Ashe1y")
    @ApiOperation(value = "删除接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "组件id", required = true)
    })
    @DeleteMapping("/{id}")
    public Result<String> delete(@PathVariable Integer id) {
        usersInfoService.removeById(id);
        return Result.success().msg("删除成功");
    }

    /**
     * 批量删除接口
     *
     * @param ids
     * @return
     */
    @ApiOperationSupport(author = "Ashe1y")
    @ApiOperation(value = "批量删除接口")
    @PostMapping("/del/batch")
    public Result<String> deleteBatch(@RequestBody List<Integer> ids) {
        usersInfoService.removeByIds(ids);
        return Result.success().msg("批量删除成功");
    }
}